package com.liveneo.stoat.common.toolbox.video;

import java.io.File;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.AudioInfo;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncoderProgressListener;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;
import it.sauronsoftware.jave.MultimediaInfo;
import it.sauronsoftware.jave.VideoAttributes;
import it.sauronsoftware.jave.VideoInfo;
import it.sauronsoftware.jave.VideoSize;

public class ConvertVideo {
	
	/**
	* 将上传的视频转换为3gp标清格式
	* 
	* @param resourceId
	* @return
	*/
	public static Map<String, Object> to3GP(String resourceId) {
		Logger logger = LoggerFactory.getLogger(ConvertVideo.class);
		
		String sourcePath = "D:/test";
		String sourceFilePath = sourcePath + "/" + resourceId;
		logger.info("--------------------sourceFilePath:" + sourceFilePath);
		String targetSourceId = (resourceId.substring(0,resourceId.lastIndexOf(".")))+ ".3gp";
		String targetFilePath = sourcePath + "/" + targetSourceId;
		logger.info("--------------------targetFilePath:" + targetFilePath);


		Map<String, Object> returnMap = Maps.newHashMap();
		File source = new File(sourceFilePath);
		File target = new File(targetFilePath);
		Encoder encoder = new Encoder();
		MultimediaInfo info=null;
		if(!source.exists()){
			logger.info("source not exists");
		}
		try {
			info = encoder.getInfo(source);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		// 获取源文件的视频信息
		VideoInfo videoInfo = info.getVideo();
		int vodeoBitRate=videoInfo.getBitRate(); //总比特率
		int videoFrameRate=(int)videoInfo.getFrameRate();//帧速率
		String videoDecoder=videoInfo.getDecoder();
		VideoSize videoSize = videoInfo.getSize();



		// 获取源文件的音频信息
		AudioInfo audioInfo = info.getAudio();
		int audioBitRate=audioInfo.getBitRate();//比特率
		String audioDecoder=audioInfo.getDecoder();
		int audioChannel = audioInfo.getChannels();// 频道
		int audioSimplingRate = audioInfo.getSamplingRate();// 音频采样频率
		
		
		AudioAttributes audio = new AudioAttributes();
		audio.setCodec("libfaac");
		audio.setBitRate(new Integer(8));
		audio.setSamplingRate(new Integer(audioSimplingRate / 2));
		audio.setChannels(new Integer(audioChannel));
		
		
		VideoAttributes video = new VideoAttributes();
		
		//VideoAttributes.DIRECT_STREAM_COPY
		video.setCodec("mp4");
		video.setBitRate(new Integer(100000));
		video.setFrameRate(new Integer(16));
		video.setSize(new VideoSize((int) (videoSize.getWidth() / 4),(int) (videoSize.getHeight() / 4)));
		
		
		EncodingAttributes attrs = new EncodingAttributes();
		attrs.setFormat("3gp");
		attrs.setAudioAttributes(audio);
		attrs.setVideoAttributes(video);


		try {
			encoder.encode(source, target, attrs);
		} catch (Exception e) {
			logger.error(e.getMessage());
			targetSourceId="";
		}

		logger.info("--------------------sourceSize:" + source.length());
		logger.info("--------------------targetSize:" + target.length());
		returnMap.put("resourceID", targetSourceId);
		Integer resourceSize=(int) target.length();
		returnMap.put("resourceSize", resourceSize);
		return returnMap;
	}
	
	public boolean formatVideoToMp4( String originFilePath, String destinationFilePath, int videoBitrate )
	  {
	      File source = new File( originFilePath ) ;
	      File target  = new File( destinationFilePath ) ;

	      Encoder encoder = new Encoder();
	      
	      AudioAttributes audio = new AudioAttributes();
	      audio.setCodec("libfaac");
	      audio.setBitRate(new Integer(128000));
	      audio.setChannels(new Integer(2));
	      audio.setSamplingRate(new Integer(44100));

	      VideoAttributes video = new VideoAttributes();
	      //VideoAttributes.DIRECT_STREAM_COPY
	      video.setCodec(VideoAttributes.DIRECT_STREAM_COPY);		//mpeg4
	      video.setBitRate(new Integer(videoBitrate));
	      video.setFrameRate(new Integer(30));
	      video.setSize( new VideoSize( 480, 360 ) ) ;
	      
	      try
	      {
	          MultimediaInfo info = encoder.getInfo( source ) ;
	          video.setSize( info.getVideo( ).getSize( ) ) ;
	      }
	      catch ( InputFormatException e1 )
	      {
	          e1.printStackTrace();
	      }
	      catch ( EncoderException e1 )
	      {
	          e1.printStackTrace();
	      }
	      
	      

	      EncodingAttributes attrs = new EncodingAttributes();
	      attrs.setFormat("3gp");
	      attrs.setAudioAttributes( audio );
	      attrs.setVideoAttributes( video );
	      try
	      {
	          encoder.encode(source, target, attrs);
	      }
	      catch ( IllegalArgumentException e )
	      {
	          e.printStackTrace();
	      }
	      catch ( InputFormatException e )
	      {
	          e.printStackTrace();
	      }
	      catch ( EncoderException e )
	      {
	          e.printStackTrace();
	      }
	      /*String command = "ffmpeg -i \"" + originFilePath + "\" -b " + videoBitrate + "k \"" + destinationFilePath + "\"" ;
	      commands.add( command ) ;
	      
	      String[] commandsArr = new String[]
	{
	      	"ffmpeg", "-i", originFilePath, "-b", String.valueOf(videoBitrate) + "k", destinationFilePath
	} ;
	      arrayCommands.add(commandsArr);
	      */
	      return true ;
	  }
	
	/**
	 * Converts Mp4 file to MP3
	 *
	 * @param fileMp4
	 * @param fileMp3
	 * @return true if it has been converted
	 */
	public static boolean mp4ToMp3(File fileMp4, File fileMp3)
	{
		Logger logger = LoggerFactory.getLogger(ConvertVideo.class);
		AudioAttributes audio = new AudioAttributes();
		audio.setCodec("libmp3lame");
		audio.setBitRate(new Integer(128000));
		audio.setChannels(new Integer(2));
		audio.setSamplingRate(new Integer(44100));
		EncodingAttributes attrs = new EncodingAttributes();
		attrs.setFormat("mp3");
		attrs.setAudioAttributes(audio);
		Encoder encoder = new Encoder();
		try
		{
			encoder.encode(fileMp4, fileMp3, attrs);
			logger.info("File MP4 convertito in MP3");
			return true;
		}
		catch (IllegalArgumentException | EncoderException e)
		{
			logger.error("File non convertito>>" + e.getStackTrace());
			return false;
		}
	}
	
	public static boolean mp4ToFlv(File fileMp4, File fileMp3)
	{
		Logger logger = LoggerFactory.getLogger(ConvertVideo.class);
		AudioAttributes audio = new AudioAttributes();
		audio.setCodec("libmp3lame");
		audio.setBitRate(new Integer(128000));
		audio.setChannels(new Integer(2));
		audio.setSamplingRate(new Integer(44100));
		EncodingAttributes attrs = new EncodingAttributes();
		attrs.setFormat("flv");
		attrs.setAudioAttributes(audio);
		Encoder encoder = new Encoder();
		try
		{
			encoder.encode(fileMp4, fileMp3, attrs);
			logger.info("File MP4 convertito in MP3");
			return true;
		}
		catch (IllegalArgumentException | EncoderException e)
		{
			logger.error("File non convertito>>" + e.getStackTrace());
			return false;
		}
	}
	
	public static boolean mp4To3gp(File fileMp4, File fileMp3)
	{
		Logger logger = LoggerFactory.getLogger(ConvertVideo.class);
		AudioAttributes audio = new AudioAttributes();
		audio.setCodec("libmp3lame");
		audio.setBitRate(new Integer(128000));
		audio.setChannels(new Integer(2));
		audio.setSamplingRate(new Integer(44100));
		EncodingAttributes attrs = new EncodingAttributes();
		attrs.setFormat("3gp");
		attrs.setAudioAttributes(audio);
		Encoder encoder = new Encoder();
		try
		{
			encoder.encode(fileMp4, fileMp3, attrs);
			logger.info("File MP4 convertito in MP3");
			return true;
		}
		catch (IllegalArgumentException | EncoderException e)
		{
			logger.error("File non convertito>>" + e.getStackTrace());
			return false;
		}
	}
	
	
	/**   分割视频   */
	public boolean splitVideo( String originalFile, String destinationFile, float secondsInit, float duration, int bitrate )
	{
	    File source = new File( originalFile ) ;
	    File target  = new File( destinationFile ) ;

	    Encoder encoder = new Encoder();
	    
	    AudioAttributes audio = new AudioAttributes();
	    audio.setCodec("libfaac");
	    audio.setBitRate(new Integer(128000));
	    audio.setChannels(new Integer(2));
	    audio.setSamplingRate(new Integer(44100));
	    
	    VideoAttributes video = new VideoAttributes();
	    video.setCodec("mpeg4");
	    video.setBitRate(new Integer(bitrate));
	    video.setFrameRate(new Integer(30));
	    video.setSize( new VideoSize( 480, 360 ) ) ;
	    
	    EncodingAttributes attrs = new EncodingAttributes();
	    
	    attrs.setFormat("mp4");
	    attrs.setAudioAttributes( audio );
	    attrs.setVideoAttributes( video );
	    attrs.setDuration( duration ) ;
	    attrs.setOffset( secondsInit ) ;
	    
	    try
	    {
	        EncoderProgressListener listener = new EncoderProgressListener( )
	        {
	            
	            @Override
	            public void sourceInfo( MultimediaInfo arg0 )
	            {
	                // TODO Auto-generated method stub
	                
	            }
	            
	            @Override
	            public void progress( int arg0 )
	            {
	                System.out.println( "Progresso da diviso de arquivos: " + arg0 );
	            }
	            
	            @Override
	            public void message( String arg0 )
	            {
	                System.out.println( arg0 );
	            }
	        };
	        encoder.encode(source, target, attrs, listener);
	    }
	    catch ( IllegalArgumentException e )
	    {
	        e.printStackTrace();
	    }
	    catch ( InputFormatException e )
	    {
	        e.printStackTrace();
	    }
	    catch ( EncoderException e )
	    {
	        e.printStackTrace();
	    }
	    return true ;
	}
	
	/**===================  avi格式转3gp   ======================
	 * @throws EncoderException 
	 * @throws InputFormatException 
	 * @throws IllegalArgumentException */
	public void aviTo3gp() throws IllegalArgumentException, InputFormatException, EncoderException{
		File source = new File("source.avi");
		File target = new File("target.3gp");
		AudioAttributes audio = new AudioAttributes();
		audio.setCodec("libfaac");
		audio.setBitRate(new Integer(128000));
		audio.setSamplingRate(new Integer(44100));
		audio.setChannels(new Integer(2));
		VideoAttributes video = new VideoAttributes();
		video.setCodec("mpeg4");
		video.setBitRate(new Integer(160000));
		video.setFrameRate(new Integer(15));
		video.setSize(new VideoSize(176, 144));
		EncodingAttributes attrs = new EncodingAttributes();
		attrs.setFormat("3gp");
		attrs.setAudioAttributes(audio);
		attrs.setVideoAttributes(video);
		Encoder encoder = new Encoder();
		encoder.encode(source, target, attrs);
	}
}
